package net.pws.oos.biz.bdmap;

import java.util.List;

import net.pws.common.event.ApplicationEventBus;
import net.pws.common.event.ApplicationEventListener;
import net.pws.common.event.ApplicationEventObject;
import net.pws.common.persistence.EntityManager;
import net.pws.common.simplemq.DefaultDataQueueProcessor;
import net.pws.common.simplemq.MessageSender;
import net.pws.oos.biz.event.TaskCompletedEventObject;
import net.pws.oos.biz.model.Task;
import net.pws.oos.biz.query.TaskFinder;
import net.pws.oos.biz.service.MapService;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

@Component
public class UpdateLocationAddressListener implements ApplicationEventListener,
		InitializingBean {

	@Autowired
	private TaskFinder taskFinder;

	@Autowired
	private EntityManager entityManager;

	@Autowired
	private MapService mapService;
	
	private DefaultDataQueueProcessor processor;

	public UpdateLocationAddressListener() {
		ApplicationEventBus.getInstance().addListener(this);
	}

	public boolean support(ApplicationEventObject event) {
		return (event instanceof TaskCompletedEventObject);
	}

	public void handle(ApplicationEventObject event) {
		String id = (String) event.getSource();
		List<Task> taskList = taskFinder.getNoAddressTaskList(id);
		for (Task task : taskList) {
			processor.getDataPipe().addData(task);
		}
	}

	public void afterPropertiesSet() throws Exception {
		Assert.notNull(mapService);
		Assert.notNull(entityManager);
		processor = new DefaultDataQueueProcessor(new MessageSender(
				new LocationAddressUpdater(entityManager, mapService)), 1);
		List<Task> taskList = taskFinder.getNoAddressTaskList(null);
		for (Task task : taskList) {
			processor.getDataPipe().addData(task);
		}
	}

}
